import { Singleton } from "../common/Singleton";



export type event_callback = (...params: any[]) => void
export class EventMgr extends Singleton {
    eventArray: { obj: object, eventName: string, eventFunc: event_callback }[] = [];

    /**
     * 添加事件监听
     * @param obj 对象
     * @param eventName 监听名称 
     * @param eventFunc 监听方法
     */
    on(obj: object, eventName: string, eventFunc: event_callback) {
        let e = this.eventArray.find(e => e.eventName == eventName && e.obj == obj)
        if (e)
            e.eventFunc = eventFunc
        else
            this.eventArray.push({ obj: obj, eventName: eventName, eventFunc: eventFunc })
    }

    /**
     * 移除一个事件
     * @param obj 
     * @param eventName 
     */
    off(obj: object, eventName: string) {
        let index = this.eventArray.findIndex(e => e.obj == obj && e.eventName == eventName)
        if (index >= 0)
            this.eventArray.splice(index, 1)
    }

    /**
     * 移除所有事件
     * @param obj 
     */
    offAll(obj: object) {
        for (let i = 0; i < this.eventArray.length; i++) {
            if (this.eventArray[i].obj == obj) {
                this.eventArray.splice(i, 1);
                i--;
            }
        }
    }

    /**
     * 判断监听事件
     * @param eventName 
     * @returns 
     */
    has(eventName: string): boolean {
        return !!this.eventArray.find(e => e.eventName == eventName);
    }

    /**
     * 执行事件
     * @param eventName 
     * @param params 
     */
    emit(eventName: string, ...params: any[]) {
        const arr = this.eventArray.filter(a => a.eventName == eventName)
        for (let i = 0; i < arr.length; i++) {
            const e = arr[i];
            try {
                e.eventFunc.apply(e.obj, [...params]);
            } catch (error) {
                console.error(error)
            }
        }
    }
}
/**
 * 事件管理
 */
export const eventMgr = EventMgr.getInstance<EventMgr>()


